#include "parameters.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>

int err_threshold(int threshold) {
  return !(threshold >= 0 && threshold <= 255);
}

int err_mode(int mode) {
  return !(mode == 0 || mode == 1);
}

void print_help(const char *exec_name) {
  printf("Usage: %s [options] <file>\n", exec_name);
  printf("Non-optional arguments:\n");
  printf("<file>\t\tinput file (<filename>.bmp)\n");
  printf("Allowed options:\n");
  printf("-h\t\tthis help message\n");
  printf("-v\t\tverbose mode\n");
  printf("-t arg\t\tthreshold (0 <= arg <= 255) ");
  printf("[default: %d]\n", DEF_THRESHOLD);
  printf("-m arg\t\tmode (0: encode, 1: decode) ");
  printf("[default: %d]\n", DEF_MODE);
  printf("-o arg\t\toutput filename (<filename>.bmp) ");
  printf("[default: %s]\n", DEF_OUT_FNAME);
}

//parsing
void get_arguments(char *argv[], int argc, arguments *args) {
  args->verbose = 0;
  args->threshold = DEF_THRESHOLD;
  strcpy(args->out_fname, DEF_OUT_FNAME);
  args->mode = DEF_MODE;
  const char *options = "m:t:o:vh";
  int opt;
  opterr = 0;
  while((opt = getopt(argc, argv, options)) != -1) {
    switch(opt) {
    case 'm': //mode
      args->mode = (unsigned int)atoi(optarg);
      if(err_mode(atoi(optarg))) {
	printf("ERROR in argument: m\n");
	print_help(argv[0]);
	exit(1);
      }
      break;
    case 't': //threshold
      args->threshold = (unsigned int)atoi(optarg);
      if(err_threshold(atoi(optarg))) {
	printf("ERROR in argument: t\n");
	print_help(argv[0]);
	exit(1);
      }
      break;
    case 'o': //threshold
      strcpy(args->out_fname, optarg);
      break;
    case 'h': //help
      print_help(argv[0]);
      exit(0);
    case 'v': //help
      args->verbose = 1;
      break;
    case '?': //parsing error
      printf("Illegal options\n");
      print_help(argv[0]);
      exit(1);
    }
  }
  //parse non-optional arguments
  if(optind < argc)
    strcpy(args->fname, argv[optind]);
  else {
    printf("ERROR: no input file provided\n");
    exit(1);
  }
}
